package store.swing.order;

import store.domain.Product;
import store.swing.DefaultTable;
import store.swing.product.ProductInfoFrame;
import store.swing.product.ProductTableModel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

public class OrderItemTable extends DefaultTable {
    private static final OrderItemTableModel TABLE_MODEL = new OrderItemTableModel();
    private static final Font HEADER_FONT = new Font("Tahoma", Font.BOLD, 13);
    private static final Font TABLE_FONT = new Font("Tahoma", Font.PLAIN, 13);

    public OrderItemTable() {
        super(TABLE_MODEL);
        getTableHeader().setFont(HEADER_FONT);
        setFont(TABLE_FONT);
        addMouseListener(new TableMouseListener());
        setColumnSize(0, null, 25, 25);
        setColumnSize(1, 0, 0, 0);
        setColumnSize(2, 200, null, null);
        filterByColumn(1);
    }

    private void setColumnSize(int index, Integer minWidth, Integer maxWidth, Integer preferredWidth) {
        if (minWidth != null) {
            getColumnModel().getColumn(index).setMinWidth(minWidth);
        }
        if (maxWidth != null) {
            getColumnModel().getColumn(index).setMaxWidth(maxWidth);
        }
        if (preferredWidth != null) {
            getColumnModel().getColumn(index).setPreferredWidth(preferredWidth);
        }
    }

    private void filterByColumn(int columnIndex) {
        String text = OrderTable.getSelectedOrder().getOrderId().toString();
        if (text.length() == 0) {
            getSorter().setRowFilter(null);
        } else {
            getSorter().setRowFilter(RowFilter.regexFilter(text, columnIndex));
        }
    }

    private class TableMouseListener extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                String productEan = (String) getValueAt(getSelectedRow(), 4);
                List<Product> products = ProductTableModel.getProducts();
                Product selectedProduct = null;
                for (Product product : products) {
                    if (productEan.equals(product.getProductEan())) {
                        selectedProduct = product;
                        break;
                    }
                }
                new ProductInfoFrame(selectedProduct).setVisible(true);
            }
        }
    }
}
